<?php
/**
 * Created by PhpStorm.
 * User: 1
 * Date: 2018/3/22
 * Time: 13:39
 */

namespace app\api\model;
use think\Model;
use think\Db;
use think\Log;
use think\Cache;
use app\common\lib\exception\ApiException;

class Order extends Model
{
    /**
     * 查询学生在上的学费课程、学币课程或者以及已上完的课程
     * @author 巫玉梅 <1120504614@qq.com>
     * @return array|string|\think\response\Json
     */
    public function getAllOrderLesson(){
        if (empty($_POST)) {
            throw new ApiException('数据不合法',401);
        }
        //id int user_id 学生用户id
        if (empty($_POST['id'])) {
            throw new ApiException('id is not found',404);
        }
        //* @param status int 已上完的课程和在上课程的按钮状态 完结1 在上学费2 在上的学币课3
        $where = "";

        if (empty($_POST['status'])) {

            throw new ApiException('status is not found',404);

        } elseif (!empty($_POST['status'])) {
            if ($_POST['status'] == 1) { // 已上完的课程 实际上完+教师停课+学生停课+差评课程
                $where = '(order.user_id="' . $_POST['id'] . '" AND lesson.lesson_num=lesson.com_lesson_num) OR (order.user_id="'. $_POST['id'] .'"AND lesson_comment.comment_rank>3)';
            } elseif ($_POST['status'] == 2) { //在上的学费课状态
                $where = 'order.user_id="' . $_POST['id'] . '" AND lesson.lesson_num>lesson.com_lesson_num AND lesson.cost_type=1 AND lesson_comment.comment_rank<4';
            } elseif ($_POST['status'] == 3) { //在上的学币课状态
                $where = 'order.user_id="' . $_POST['id'] . '" AND lesson.lesson_num>lesson.com_lesson_num AND lesson.cost_type=2';
            }
        }

        try {
            $order = Db::name('order')
                ->alias("order")
                ->where($where)
                ->join('lesson', 'lesson_id=lesson.id', 'LEFT')
                ->join('subject ', 'subject_id=subject.id', 'LEFT')
                ->join('lesson_program ', 'program_id=lesson_program.id', 'LEFT')
                ->join('service_target ', 'service_target_id=service_target.id', 'LEFT')
                ->join('lesson_nature ', 'lesson_nature_id=lesson_nature.id', 'LEFT')
                ->join('user ', 'teacher_id=user.id', 'LEFT')
                ->join('classroom ', 'classroom_id=classroom.id', 'LEFT')
                ->join('city ', 'lesson.city_id=city.id', 'LEFT')
                ->join('lesson_comment', 'order.user_id = lesson_comment.comment_id AND order.id  =lesson_comment.ord_id', 'LEFT')
                ->join('lesson_num_time', 'lesson_num_time.lesson_id=lesson.id AND lesson_num_time.lesson_number  =lesson.lesson_num', 'LEFT')
                ->field('order.lesson_id,lesson.id,lesson.lesson_sn,subject.subject,lesson_program.program,lesson.lesson_method,lesson.is_comment,lesson.lesson_cost,lesson.cost_type,lesson.lesson_name,lesson.com_lesson_num,lesson.lesson_num,lesson_comment.comment_status,
order_sn,lesson.is_reclass,lesson_num_time.lesson_end_time,lesson_comment.comment_rank')
                ->order('order.id desc')
                ->select();

            if(!empty($order)){
                foreach($order as $k => $v){
                    $reclass = Db::name('reclass')
                        ->alias("reclass")
                        ->where('reclass.reclass_stu_id',$_POST['id'])
                        ->where('reclass.reclass_les_id',$v['id'])
                        ->field("reclass.reclass_status")
                        ->find();
                    if(!empty($reclass)){
                        $order[$k]['reclass_status'] = $reclass['reclass_status'];
                    }
                }
            }

            return show(config('code.success'), '获取数据成功', $order, 200);

        } catch (\Exception $e) {
            Log::write($e->getMessage());
            throw new ApiException($e->getMessage(),400);
        }
    }

    /**
     * 检查订单信息
     * @param id int 用户id *必传
     * @param lesson_id int 课程id *必传
     * @param is_approve int 是否审核 0待审核 1已审核 2已开课 默认为1
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array|string|\think\response\Json
     */
    public function checkOrder(){
        $data = $_POST;
        if(empty($data)) {
            throw new ApiException('数据不合法',404);
        }

        if(!isset($data['id'])){
            throw new ApiException('id is not found',404);
        }

        //课程id
        if(!isset($data['lesson_id'])){
            throw new ApiException('lesson_id is not found',404);
        }

        try{
            $order = $this
                ->where('lesson_id='.$data['lesson_id'].' AND user_id='.$data['id'])
                ->find();

            return show(config('code.success'), 'ok！', $order);

        }catch (\Exception $e){
            Log::write($e->getMessage());
            throw new ApiException($e->getMessage(),400);
        }
    }

    /**
     * 生成购买课程待支付订单
     * @param int user_id 用户id *必传
     * @param int lesson_id 课程id *必传
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array|string|\think\response\Json
     */
    public function addOrder(){
        if (empty($_POST)) {
            throw new ApiException('数据不合法！',401);
        }
        if (empty($_POST['user_id']) && !isset($_POST['user_id'])) {
            throw new ApiException('user_id is not found',404);
        }

        if (empty($_POST['lesson_id']) && !isset($_POST['lesson_id'])) {
            throw new ApiException('lesson_id is not found',404);
        }

        try{
            // 查询正在上课的名额
            $count = (new LessonComment())
                ->where('lesson_id='.$_POST['lesson_id'])
                ->where('comment_rank','<','4')
                ->field('id')
                ->count();

            $led = (new Lesson())
                ->where('id='.$_POST['lesson_id'])
                ->field('lesson_sn,lesson_name,lesson_cost,max_person,registration_end_time,is_approve,cost_type')
                ->find();

            //最大下单数
            $max_person = $led->max_person;

            //报名截止时间
            $end_enroll_time = $led->registration_end_time;

            //订单时间
            $_POST['order_time'] = time();
            $order_num = $this->field('order_sn')->select();
            if ($order_num) {
                $arr = [];
                foreach ($order_num as $k => $v) {
                    $arr[] = substr($order_num[$k]->order_sn,-4);
                }

                //生成订单编号
                $_POST['order_sn'] = substr(date('Y'),2,2).date('mdHis').$led->lesson_sn.sprintf("%04d",max($arr) + 1);
            }else{
                //生成订单编号
                $_POST['order_sn'] = substr(date('Y'),2,2).date('mdHis').$led->lesson_sn.sprintf("%04d",1);
            }

            //获取已审核通过的课程编号
            $_POST['order_lesson_sn'] = $led->lesson_sn;

            //订单状态 0未完结 1已完结
            $_POST['order_status'] = 0;

            //支付状态 0未支付 1已支付
            //$_POST['pay_status'] = 0;

            //$end_enroll_time 截止报名时间
            $time = $end_enroll_time - $_POST['order_time'];

            $order_record = $this
                ->where('lesson_id='.$_POST['lesson_id'].' AND user_id='.$_POST['user_id'])
                ->field('pay_status,order_sn')
                ->find();

            //课程是否审核 1已审核
            if( $led->is_approve != 1){
                return show(config('code.error'),'该课程未通过审核！');
            }

            //报名时间判断
            if ($time < 0 || $time == 0){
                return show(config('code.error'), '已过报名截止时间！');
            }

            //报名人数判断
            if (($max_person - $count < 0 || $max_person - $count == 0) && $max_person != 0){
                return show(config('code.error'), '课程报名人数已满！');
            }

            if($order_record['pay_status'] == 1){
                return show(config('code.error'), '已购买该课程！');
            }

            $_POST['cost_type'] = 2;
            $_POST['account_type'] = 3;
            $_POST['cost_description'] = '购买课程';

            //设置订单支付有效期为10分钟
            Cache::set('order:'.$_POST['order_sn'],$_POST,10*60);

            //创建支付订单
            $return = [
                'body' => $led->lesson_name,
                'subject' => '购买课程',
                'out_trade_no' => $_POST['order_sn'],
                'total_amount' => $led->lesson_cost,
            ];

            return show(config('code.success'),'下单成功！',$return);

        }catch (\Exception $e){
            Log::write($e->getMessage());
            throw new ApiException($e->getMessage(),500);
        }
    }

    /**
     * 支付订单
     * @param string body 交易描述 *必传
     * @param string subject 标题 *必传
     * @param string out_trade_no 订单编号 *必传
     * @param float total_amount 交易金额 *必传
     * @param string pay_password 支付密码 *必传
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array|string|\think\response\Json
     */
    public function PayOrder(){
        $data = $_POST;

        if (empty($data)) {
            throw new ApiException('数据不合法！',401);
        }

        if (empty($data['body']) && !isset($data['body'])) {
            throw new ApiException('body(交易描述) is not found',404);
        }

        if (empty($data['subject']) && !isset($data['subject'])) {
            throw new ApiException('subject(标题) is not found',404);
        }

        if (empty($data['out_trade_no']) && !isset($data['out_trade_no'])) {
            throw new ApiException('out_trade_no(订单编号) is not found',404);
        }

        if (empty($data['total_amount']) && !isset($data['total_amount'])) {
            throw new ApiException('total_amount(订单金额) is not found',404);
        }

        if (empty($data['pay_password']) && !isset($data['pay_password'])) {
            throw new ApiException('pay_password(支付密码) is not found',404);
        }



        Db::startTrans();

        try{
            //查询订单信息
            $order_sn = Cache::get('order:'.$data['out_trade_no']);

            $unique = Db::name('order')->where('order_sn',$data['out_trade_no'])->find();
            if($unique){
                return show(config('code.error'), '当前订单已存在');
            }

            if($order_sn){
                //根据课程id查询课程信息
                $led = (new Lesson())->getLessonByLessonId($order_sn['lesson_id']);

                //根据学生id查询学生信息
                $student = (new Student())->getStudentMoneyByStudentId($order_sn['user_id']);

                //判断支付类型检测余额状态
                if($led->cost_type == 1){

                    //学费余额
                    if($student['tuition'] - $led->lesson_cost < 0){
                        return show(config('code.error'), '学费余额不足！');
                    }

                    //支付密码
                    $pay_password = db('user')->where('id='.$order_sn['user_id'])->field('pay_password')->find();

                    if(empty($pay_password['pay_password'])){
                        return show(config('code.error'), '你还未设置支付密码！');
                    }

                    if(md5($data['pay_password']) != $pay_password['pay_password']){
                        return show(config('code.error'), '支付密码不正确！');
                    }

                    //支付学费订单
                    $tuition['tuition'] = $student['tuition'] - $led->lesson_cost;
                    $students = new Student();
                    $status =  $students
                        ->allowField(true)
                        ->where(array('student_id' => $order_sn['user_id']))
                        ->update($tuition);

                    if($status){
                        //保存支付成功订单信息
                        $order = new Order();

                        //支付状态 0未支付 1已支付
                        $order_sn['pay_status'] = 1;

                        $order->allowField(true)->save($order_sn);

                        $comment = new LessonComment();

                        $commentData = [
                            //评论课程id
                            'lesson_id' => $order_sn['lesson_id'],

                            //评论课程sn
                            'comment_lesson_sn' => $order_sn['order_lesson_sn'],

                            //评论课程时间
                            'comment_time' => time(),

                            //评论等级
                            'comment_rank' => 1,

                            //评论用户id
                            'comment_id' => $order_sn['user_id'],

                            //评论状态 0不评论 1需要评论
                            'comment_status' => 1,

                            //订单id
                            'ord_id' => $order->getLastInsID(),
                        ];

                        //插入相关信息到评论表
                        $comment->allowField(true)->save($commentData);

                        $settlement = new Settlement();

                        //订单id
                        $set['order_id'] = $commentData['ord_id'];

                        //插入相关信息到结算表
                        $settlement->allowField(true)->save($set);

                        $accounts = new Account();
                        $accounts::addAccount($order_sn['order_sn'],$order_sn['user_id'],'购买课程',-$data['total_amount'],2,'remain');

                        //发送消息通知
                        SendMessage($order_sn['user_id'],'购买课程',date('Y-m-d H:i:s').' 课程购买成功！订单号【'.$order_sn['order_sn'].'】请在我的课程中查看详情信息！');

                        Db::commit();
                        return show(config('code.success'),'支付成功！');
                    }else{
                        return show(config('code.error'),'支付失败！');
                    }
                }elseif($led->cost_type == 2){
                    //学币余额
                    if($student['coin'] - $led->lesson_cost < 0){
                        return show(config('code.error'), '学币余额不足！');
                    }

                    //支付密码
                    $pay_password = db('user')->where('id='.$order_sn['user_id'])->field('pay_password')->find();

                    if(empty($pay_password['pay_password'])){
                        return show(config('code.error'), '你还未设置支付密码！');
                    }

                    if(md5($data['pay_password']) != $pay_password['pay_password']){
                        return show(config('code.error'), '支付密码不正确！');
                    }

                    //支付学币订单
                    $coin['coin'] = $student['coin'] - $led->lesson_cost;
                    $students = new Student();
                    $status =  $students
                        ->allowField(true)
                        ->where(array('student_id' => $order_sn['user_id']))
                        ->update($coin);

                    if($status){
                        //保存支付成功订单信息
                        $order = new Order();

                        //支付状态 0未支付 1已支付
                        $order_sn['pay_status'] = 1;

                        $order->allowField(true)->save($order_sn);

                        $accounts = new Account();
                        $accounts::addAccount($order_sn['order_sn'],$order_sn['user_id'],'购买课程',-$data['total_amount'],1,'remain');

                        //发送消息通知
                        SendMessage($order_sn['user_id'],'购买课程',date('Y-m-d H:i:s').' 课程购买成功！订单号【'.$order_sn['order_sn'].'】请在我的课程中查看详情信息！');

                        Db::commit();
                        return show(config('code.success'),'支付成功！');
                    }else{
                        return show(config('code.error'),'支付失败！');
                    }
                }
            }

            return show(config('code.error'),'订单信息错误！');

        }catch (\Exception $e){
            Db::rollback();
            Log::write($e->getMessage());
            throw new ApiException($e->getMessage(),500);
        }
    }
}